package cn.lijian.goods.admin.book.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import cn.lijian.goods.book.domain.Book;
import cn.lijian.goods.book.service.BookService;
import cn.lijian.goods.category.domain.Category;
import cn.lijian.goods.category.service.CategoryService;
import cn.lijian.goods.pager.PageBean;

public class AdminBookServlet extends BaseServlet {
	private CategoryService categoryService=new CategoryService();

	private BookService bookService=new BookService();
	/**
	 * 删除图书
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String delete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String bid=req.getParameter("bid");
		Book book=bookService.load(bid);
		//删除图片
		String savepath=this.getServletContext().getRealPath("/");
		System.out.println(savepath);
		new File(savepath,book.getImage_w()).delete();
		new File(savepath,book.getImage_b()).delete();
		bookService.delete(bid);
		req.setAttribute("msg", "删除图书成功");
		return "f:/adminjsps/msg.jsp";
	}
	
	/**
	 * 修改图书
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String edit(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Book book=CommonUtils.toBean(req.getParameterMap(), Book.class);
		Category category=CommonUtils.toBean(req.getParameterMap(), Category.class);
		book.setCategory(category);
		bookService.edit(book);
		req.setAttribute("msg", "修改图书成功");
		return "f:/adminjsps/msg.jsp";
	}
	
	/**
	 * 加载图书
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String load(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String bid=req.getParameter("bid");
		Book book=bookService.load(bid);
		req.setAttribute("book", book);
		req.setAttribute("parents", categoryService.findParents());
		String pid=book.getCategory().getParent().getCid();
		req.setAttribute("children", categoryService.findChild(pid));
		System.out.println(req.getAttribute("children"));
		return "f:/adminjsps/admin/book/desc.jsp";
	}
	
	/**
	 * 添加图书 第一步
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String addPre(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Category>parents=categoryService.findParents();
		request.setAttribute("parents", parents);
		return "f:/adminjsps/admin/book/add.jsp";
	}
	
	public String ajaxFindChildren(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String pid=request.getParameter("pid");
		List<Category>children=categoryService.findChild(pid);
		
		String json=toJson(children);
		response.getWriter().print(json);
		
		return null;
	}
	
	private String toJson(Category category){
		StringBuilder sb=new StringBuilder("{");
		sb.append("\"cid\"").append(":").append("\"").append(category.getCid()).append("\"");
		sb.append(",");
		sb.append("\"cname\"").append(":").append("\"").append(category.getCname()).append("\"");
		sb.append("}");
		return sb.toString();
		
	}
	
	private String toJson(List<Category>list){
		StringBuilder sb=new StringBuilder("[");
		for(int i=0;i<list.size();i++){
			sb.append(toJson(list.get(i)));
			if(i<list.size()-1){
				sb.append(",");
			}
		}
		sb.append("]");
		return sb.toString();
		
	}
	
	
	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}
	
	
	public String findCategoryAll(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<Category>parents=categoryService.findAll();
		req.setAttribute("parents", parents);
		
		return "f:/adminjsps/admin/book/left.jsp";
	}

	
	/**
	 * 获取当前页的页码
	 * @param request
	 * @return
	 * @author lijian
	 */
	private int getPageCurrent(HttpServletRequest request){
		int pc=1;
		String param=request.getParameter("pc");
		if(param!=null&&!param.trim().isEmpty()){
			try {
				pc=Integer.parseInt(param);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return pc;
	}
	/**
	 * 
	 * 截取 URL 页面中的分页导航中需要使用它作为超链接的目标
	 * @param request
	 * @return
	 * @author lijian
	 */
	private String getUrl(HttpServletRequest request){
		//假设请求是   http://localhost:8080/goods/jsps/xx?sssss=s&sss=s
		String uri=request.getRequestURI();//   /goods/jsps/xx
		String str=request.getQueryString();//   xx?sssss=s&sss=s
		uri=uri+"?"+str;
		//如果 URL 中存在 pc 参数，截取掉，如果没有就行
		
		int index=uri.lastIndexOf("&pc");
		if(index!=-1){
			uri=uri.substring(0,index);
		}
		return uri;
	}
	/**
	 * 按分类查询
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String findByCategory(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到 pageCurrent，如果页面传递，获取，如果没有，设置 1
		int pc=getPageCurrent(request);
		//得到 URL 
		String url=getUrl(request);
		//得到查询条件
		String cid=request.getParameter("cid");
		//使用 service 查询,得到 pagebean
		PageBean<Book>pageBean=bookService.findByCategory(cid, pc);
		//给pagebean 设置 URL 
		pageBean.setUrl(url);
		request.setAttribute("pb", pageBean);
		return "f:/adminjsps/admin/book/list.jsp";
	}

	/**
	 * 按作者查询
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String findByAuthor(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到 pageCurrent，如果页面传递，获取，如果没有，设置 1
		int pc=getPageCurrent(request);
		//得到 URL 
		String url=getUrl(request);
		//得到查询条件
		String author=request.getParameter("author");
		//使用 service 查询,得到 pagebean
		PageBean<Book>pageBean=bookService.findByAuthor(author, pc);
		System.out.println(pageBean);
		//给pagebean 设置 URL 
		request.setAttribute("pb", pageBean);
		return "f:/adminjsps/admin/book/list.jsp";
	}

	/**
	 * 按出版社查询
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String findByPress(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到 pageCurrent，如果页面传递，获取，如果没有，设置 1
		int pc=getPageCurrent(request);
		//得到 URL 
		String url=getUrl(request);
		//得到查询条件
		String press=request.getParameter("press");
		//使用 service 查询,得到 pagebean
		PageBean<Book>pageBean=bookService.findByPress(press, pc);
		//给pagebean 设置 URL 
		pageBean.setUrl(url);
		request.setAttribute("pb", pageBean);
		return "f:/adminjsps/admin/book/list.jsp";
	}

	/**
	 * 按书名查询
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String findByBname(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到 pageCurrent，如果页面传递，获取，如果没有，设置 1
		int pc=getPageCurrent(request);
		//得到 URL 
		String url=getUrl(request);
		//得到查询条件
		String bname=request.getParameter("bname");
		//使用 service 查询,得到 pagebean
		PageBean<Book>pageBean=bookService.findByBname(bname, pc);
		//给pagebean 设置 URL 
		pageBean.setUrl(url);
		request.setAttribute("pb", pageBean);
		return "f:/adminjsps/admin/book/list.jsp";
	}
	
	/**
	 * 多条件组合 查询
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	public String findByCombination(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到 pageCurrent，如果页面传递，获取，如果没有，设置 1
		int pc=getPageCurrent(request);
		//得到 URL 
		String url=getUrl(request);
		//得到查询条件
		
		Book book=CommonUtils.toBean(request.getParameterMap(), Book.class);
		
		//使用 service 查询,得到 pagebean
		PageBean<Book>pageBean=bookService.findByCombination(book, pc);
		//给pagebean 设置 URL 
		pageBean.setUrl(url);
		request.setAttribute("pb", pageBean);
		return "f:/adminjsps/admin/book/list.jsp";
	}
}
